package com.example.springsecurity.controller;

import com.example.springsecurity.mapper.UserMapper;
import com.example.springsecurity.pojo.LoginVO;
import com.example.springsecurity.pojo.MyUser;
import com.example.springsecurity.pojo.RegisterRequest;
import com.example.springsecurity.pojo.Result;
import com.example.springsecurity.service.UserDetailsServiceImpl;
import com.example.springsecurity.utils.SMSUtil;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
public class RegisterController {
    @Resource
    private UserDetailsServiceImpl service;
    @Resource
    private UserMapper userMapper;
    @Resource
    private SMSUtil smsUtil;

    @RequestMapping("/test2")
    public String test2() {
        return "test2";
    }

    //发送短信验证码接口
    @PostMapping("/sendSms")
    public Result sendSms(@RequestBody Map<String,String> map) {
        String phone = map.get("phone");
        String sms = smsUtil.generateSms(phone);//得到验证码
        Integer code=500;
        String message="发送失败";
        Object data=null;
        if(sms != null) {
            code=200;
            message="发送成功";
            data=sms;

        }
        return new Result(code,message,data);
    }

    //注册接口
    @RequestMapping("/register")
    public Result register(@RequestBody RegisterRequest request) {
        //security会自动将请求体中的json数据转换为LoginVO对象
        //service默认防火墙不支持post请求，需要在配置文件中配置,禁用csrf
        //请求体中获取用户名和密码，不需要验证码

        String username = request.getUsername();
        String password = request.getPassword();
        String phone = request.getPhone();
        String sms = request.getSms();

        //根据用户名查询用户
        MyUser myUser = userMapper.getUserByUsername(username);
        //验证短信验证码sms是否正确
        boolean smsIstrue = smsUtil.validateSms(phone,sms);
        if(smsIstrue==false){
            return new Result(401,"验证码错误",null);
        }
        if(myUser==null&&smsIstrue){
            //未查询到，则用户名不重复，并且验证码正确，可以注册
            //String role = myUser.getRole();//获取用户角色?

            UserDetails user=User.builder()
                    .username(username)
                    .password(password)//加密后的密码就在service层和mapper层存在了
                    .roles("user")//默认为user
                    .build();
            service.createUser(user);
            return Result.success("注册成功");
        }else {
            //查询到，用户名重复，不可注册
            return new Result(1,"用户名重复",null);
        }


    }
}
